<template>
  <div class="search">
    <div class="searchbar">
      <input
      type="text"
      class="text"
      :placeholder="text"
      v-model="searchText">
    </div>
    <div class="search-wrapper"  v-if="searchText">
      <ul class="search-result">
        <li class="result-item border-bottom"
          v-for="(item,index) of searchResult"
          :key="index"
          @click="chooseCity(item)">{{item}}
        </li>
        <li class="result-item no-result" v-if="hasNoData">该城市不存在</li>
      </ul>
    </div>
  </div>
</template>
<script>
import { mapMutations } from 'vuex'
import { debounce } from '@/assets/js/util.js'
export default {
  name: 'search',
  data () {
    return {
      searchText: '',
      searchResult: []
    }
  },
  computed: {
    hasNoData () {
      return !this.searchResult.length
    }
  },
  watch: {
    searchText: // 搜索词发生变化显示搜索结果
      debounce(function () {
        console.log(this.searchText)
        this.search(this.searchText)
      }, 100)
  },
  props: {
    text: {
      type: String,
      default: '请输入内容'
    },
    cities: Object
  },
  methods: {
    ...mapMutations({ changeCity: 'changeCity' }),
    search (city) {
      this.searchResult = []
      for (const key in this.cities) {
        this.cities[key].forEach(item => {
          if (item.name.indexOf(city) > -1 || item.spell.indexOf(city) > -1) {
            this.searchResult.push(item.name)
          }
        })
      }
    },
    chooseCity (value) { // 选择城市，并且跳回到首页
      this.changeCity(value)
      this.searchText = ''
      this.$router.push('/home')
    }
  }
}
</script>
<style lang="stylus" scoped>
@import '~@/assets/styles/variables'
.search
  width 100%
  .searchbar
    width 100%
    background $bgColor
    height 40px
    display flex
    justify-content center
    .text
      width 95%
      text-align center
      margin-bottom 15px
      font-size 20px
  .search-wrapper
    background #fff
    position absolute
    margin-top 100px
    left 0
    top 0
    right 0
    bottom 0
    z-index 20
    overflow scroll
    .result-item
      padding-left 20px
      font-size 20px
      line-height 2
      &.border-bottom
        border-bottom 1px solid #bbb

</style>
